/**
 @Author Zhenglinbin
 @Date 2021/5/27
 **/
import {Props} from "@/components/typing";

export default {
    has: {
        mounted: (el: HTMLElement, bind: any) => {
            let routeName = bind.instance?.$router?.currentRoute?.value?.name;
            if(!routeName) return;
            let btnPermissions = [];

            const menuString = localStorage.getItem('buttonMenu')
            if(!menuString) return;
            let menuMap = JSON.parse(menuString)
            if(menuMap && Object.keys(menuMap).length > 0) {
                let authority = menuMap[routeName];
                if(!authority) return;
                btnPermissions = JSON.parse(authority);
            }

            if (btnPermissions && btnPermissions.length > 0) {
                if (!has(btnPermissions, el.innerText)) {
                    el.parentNode?.removeChild(el);
                }
            }
        }
    }
}
const has = (btnPermissions: Props[], butName: string) => {
    if (!butName) return true;
    let isExist = false;
    let alias: Props[] = [];
    let permissions: Props[] = [];

    const roles = localStorage.getItem('roles')
    if(!roles) return true;
    const positions: Props[] = JSON.parse(roles)
    if(!positions || positions.length < 1) return true

    positions.forEach(item => {
        alias.push(item.code);
    });
    btnPermissions.forEach(item => {
        if (item.name === butName.trim()) {
            permissions.push(...item.roles)
        }
    });

    if (permissions.length < 1) return true;
    alias.some(item => {
        if (permissions.includes(item)) {
            isExist = true;
            return true
        }
    });
    return isExist;
}
